package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.*;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-22
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private FamilyMemberElderService familyMemberElderService;

    @Autowired
    private IElderService elderService;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private IDeviceService deviceService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private WechatService wechatService;

    private List<String> nickNameList = Arrays.asList("好柿开花", "大吉大利", "今晚吃鸡", "三羊开泰");

    @Autowired
    private TokenService tokenService;

    /**
     * 微信小程序登录接口
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginDto dto) {
        //1. 获取微信唯一身份标识openId
        String openId = wechatService.getOpenId(dto.getCode());

        //2. 根据openId查询用户
        FamilyMember member = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();

        //3. 如果用户不存在则新增用户（自动注册）
        if(member==null) {
            Collections.shuffle(nickNameList);//打乱集合中元素的顺序

            //生成随机昵称
            String nickName  = nickNameList.get(0) + RandomStringUtils.randomNumeric(4);

            member = FamilyMember.builder()
                    .openId(openId) //唯一标识
                    .name(nickName)//昵称
                    .build();
            this.save(member);
        }

        //4. 如果手机号不存在则获取微信绑定的手机号
        if(StrUtil.isBlank(member.getPhone())) {
            String phoneNum = wechatService.getPhoneNum(dto.getPhoneCode());

            //5. 更新手机号到用户表
//            FamilyMember memberUpdate = FamilyMember.builder()
//                    .id(member.getId()) //更新条件
//                    .phone(phoneNum)//更新字段对应的值
//                    .build();
//            this.updateById(memberUpdate);

            if(StrUtil.isNotBlank(phoneNum)) {
                this.lambdaUpdate()
                        .eq(FamilyMember::getId, member.getId()) //更新条件
                        .set(FamilyMember::getPhone, phoneNum)//更新字段对应的值
                        .update();
            }
        }

        //6. 基于userId和昵称生成Token令牌
        String token = tokenService.createToken(
                Map.of(
                        "userId", member.getId(),
                        "nickName", member.getName()
        ));

        //7. 封装响应结果对象
        return LoginVo.builder().nickName(member.getName()).token(token).build();
    }


    @Override
    public void bindFamily(FamilyMemberElderDto dto) {
        if (ObjectUtil.isEmpty(dto)) {
            throw new BeanException("输入信息有误");
        }
        //1.查询要绑定的老人是否存在
        Elder elder = elderService.lambdaQuery().eq(StrUtil.isNotBlank(dto.getIdCard()), Elder::getIdCardNo, dto.getIdCard()).one();
        if (ObjectUtil.isEmpty(elder)) {
            throw new BeanException("没有该老人信息");
        }
        //2.获取当前用户的id
        Long userId = UserThreadLocal.getUserId();
        //3.根据id查询家属数据
        FamilyMember familyMember = this.getById(userId);
        if (ObjectUtil.isEmpty(familyMember)) {
            throw new BeanException("没有家属信息");
        }
        //4.封装客户老人数据
        FamilyMemberElder familyMemberElder = FamilyMemberElder.builder()
                .elderId(elder.getId())
                .familyMemberId(familyMember.getId())
                .createBy(userId)
                .remark(dto.getRemark())
                .build();
        //5.绑定老人
        familyMemberElderMapper.insert(familyMemberElder);
    }

    /**
     * 查询家人列表
     */
    @Override
    public List<FamilyMemberElderVo> queryFamilyMember() {
        //1.查询家人信息
        List<FamilyMemberElder> familyMemberElderList = familyMemberElderService.list();
        if (CollectionUtil.isEmpty(familyMemberElderList)) {
            throw new BeanException("没有查询到老人信息");
        }

        //2.遍历家人信息并封装
        List<FamilyMemberElderVo> FamilyMemberElderVoList = familyMemberElderList.stream().map(x -> {
            FamilyMemberElderVo familyMemberElderVo = BeanUtil.toBean(x, FamilyMemberElderVo.class);
            return familyMemberElderVo;
        }).collect(Collectors.toList());

        //3.查询老人数据
        List<Elder> elderList = elderService.list();
        if (CollectionUtil.isEmpty(elderList)) {
            throw new BeanException("没有查询到老人信息");
        }

        //4.遍历封装老人名称
        FamilyMemberElderVoList.forEach(x -> {
            elderList.forEach(elder -> {
                x.setElderName(elder.getName());
            });
        });

        return FamilyMemberElderVoList;

    }

    /**
     * 分页查询家人
     */
    @Override
    public List<PageFmailyMemberElderVo> listByPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return familyMemberElderMapper.listByPage();
    }

    /**
     * 查询健康数据
     */
    @Override
    public ListWrapper QueryDevicePropertyStatus(DeviceDto dto) {
        //1.查询设备信息
        Device device = deviceService.lambdaQuery()
                .eq(StrUtil.isNotBlank(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName())
                .eq(StrUtil.isNotBlank(dto.getProductKey()), Device::getProductKey, dto.getProductKey()).one();

        //2.根据设备id查询最新数据
        String deviceData = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_DATA_LATEST, device.getIotId());
        if (StrUtil.isBlank(deviceData)) {
            throw new BeanException("没有查询到设备数据");
        }

        //3.把从redis拿到的设备数据转集合
        List<DeviceData> deviceDataList = JSONUtil.toList(deviceData, DeviceData.class);


        //4.遍历集合封装除(HeartRate)之外的数据
        List<PropertyStatusInfo> propertyStatusInfoList = deviceDataList.stream()
                .filter(x -> !x.getFunctionId().contains("HeartRate"))
                .map(x -> {
                    String milliseconds = String.valueOf(x.getAlarmTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
                    PropertyStatusInfo build = PropertyStatusInfo.builder()
                            .identifier(x.getFunctionId())
                            .time(milliseconds)
                            .value(x.getDataValue())
                            .build();
                    return build;
                }).collect(Collectors.toList());

        //5.遍历集合只封装(HeartRate)数据
        List<PropertyStatusInfo> HeartRate = deviceDataList.stream()
                .filter(x -> x.getFunctionId().contains("HeartRate"))
                .map(x -> {
                    String milliseconds = String.valueOf(x.getAlarmTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
                    PropertyStatusInfo build = PropertyStatusInfo.builder()
                            .identifier(x.getFunctionId())
                            .time(milliseconds)
                            .value(x.getDataValue())
                            .build();
                    return build;
                }).collect(Collectors.toList());

        //6.合并集合
        Set<PropertyStatusInfo> set = CollectionUtil.unionDistinct(propertyStatusInfoList, HeartRate);

        //7.封装返回数据
        return new ListWrapper(new PropertyListVo(set));
    }

    /**
     * 解绑家人
     *
     * @param id
     */
    @Override
    public void unbind(Long id) {
        familyMemberElderMapper.deleteById(id);
    }

    /**
     * 按天统计查询指标数据
     *
     * @param dto
     */
    @Override
    public List<QueryDeviceDataVo> queryDeviceDataListByDay(QueryDeviceDataDto dto) {
        //1.拿到所有时分和平均值
       List<QueryDeviceDataVo> queryDeviceDataVoList = deviceDataMapper.queryDeviceDataListByDay(dto);

       //2.创建Map方便后续格式化时间
        Map<String, Double> hourMap = queryDeviceDataVoList.stream()
                .collect(Collectors.toMap(
                        QueryDeviceDataVo::getDateTime,
                        QueryDeviceDataVo::getDataValue,
                        (v1, v2) -> v1, // 如果有重复，保留第一个（理论上不会）
                        () -> new HashMap<>(24) // 初始化大小
                ));

        // 3. 构建完整的 24 小时结果
        List<QueryDeviceDataVo> fullResult = new ArrayList<>(24);
        for (int i = 0; i < 24; i++) {
            String hour = String.format("%02d:00", i); // 格式化为 00:00, 01:00, ..., 23:00
            Double avgValue = hourMap.getOrDefault(hour, 0.0); // 缺失则补 0.0

            QueryDeviceDataVo vo = new QueryDeviceDataVo();
            vo.setDateTime(hour);
            vo.setDataValue(avgValue);
            fullResult.add(vo);
        }

        return fullResult;

    }
//
//    /**
//     * 按天统计查询指标数据
//     *
//     * @param dto
//     */
//    @Override
//    public List<FamilyVo> queryDeviceDataListByDay(FamilyMemberDto dto) {
//        //1.转换格式，将时间毫秒值转换成LocalTime格式
//        // 在Service层方法中
//        // 使用 Instant，不进行时区转换
//        Instant startTime = Instant.ofEpochMilli(dto.getStartTime());
//        Instant endTime = Instant.ofEpochMilli(dto.getEndTime());
//
//        // 转为 Timestamp 用于 JDBC
//        Timestamp startTs = Timestamp.from(startTime);
//        Timestamp endTs = Timestamp.from(endTime);
//        //2.然后通过mapper而进行调用查询数据库
//        List<Map> list = deviceDataMapper.queryDeviceDataListByDay(startTs, endTs, dto.getIotId(), dto.getFunctionId());
//        //进行数据处理，将list里面的数据进行遍历
//        //创建一个Map集合进行数据封装
//        Map<Integer, List<Double>> hourValues = new HashMap<>();
//        for (Map map : list) {
//            LocalDateTime dateTime = (LocalDateTime) map.get("dateTime");
//            int hour = dateTime.getHour();//得到小时
//           // Double value = ((Number) map.get("dateValue")).doubleValue();
//            // 安全获取 data_value
//            Object obj = map.get("data_value");
//            double value;
//            if (obj instanceof Number) {
//                value = ((Number) obj).doubleValue();
//            } else if (obj instanceof String) {
//                value = Double.parseDouble((String) obj);
//            } else {
//                continue; // 跳过无效数据
//            }
//            hourValues.computeIfAbsent(hour, k -> new ArrayList<>()).add(value);
//
//        }
//        Map<Integer, Double> hourAvgMap = new HashMap<>();//用来存放转换完平均数后的数据
//        for (Map.Entry<Integer, List<Double>> entry: hourValues.entrySet()) {
//           int hour=  entry.getKey();
//            List<Double> values= entry.getValue();
//            //求每个时间点的平均数
//            double avg = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
//            hourAvgMap.put(hour,avg);
//        }
//        //数据封装进行最后的返回值
//        List<FamilyVo> result=new ArrayList<>();
//        for (int hour = 0; hour < 24; hour++) {
//            String timeStr = String.format("%02d:00", hour);
//            Double avgValue = hourAvgMap.getOrDefault(hour, 0.0);//没有值的话就设置成默认
//            //封装
//            FamilyVo vo = FamilyVo.builder()
//                    .dataValue(avgValue)
//                    .dateTime(timeStr)
//                    .build();
//            result.add(vo);
//        }
//        return result;
//    }

    /**
     * 按周统计查询指标数据
     *
     * @param dto
     * @return
     */
    @Override
    public List<FamilyWeekVo> queryDeviceDataListByWeek(FamilyMemberDto dto) {
       // 查询数据库中指定时间范围内的所有数据
        Instant startTime = Instant.ofEpochMilli(dto.getStartTime());
        Instant endTime = Instant.ofEpochMilli(dto.getEndTime());
        // 转为 Timestamp 用于 JDBC
        Timestamp startTs = Timestamp.from(startTime);
        Timestamp endTs = Timestamp.from(endTime);
        //然后通过mapper而进行调用查询数据库
        List<Map> list = deviceDataMapper.queryDeviceDataListByWeek(startTs, endTs, dto.getIotId(), dto.getFunctionId());
       // 按日期分组（不是小时）
        Map<LocalDate, List<Double>> hourValues = new HashMap<>();
        for (Map map : list) {
            LocalDateTime dateTime = (LocalDateTime) map.get("dateTime");
            LocalDate date = dateTime.toLocalDate();//得到小时
// Double value = ((Number) map.get("dateValue")).doubleValue();
            // 安全获取 data_value
            Object obj = map.get("data_value");
            double value;
            if (obj instanceof Number) {
                value = ((Number) obj).doubleValue();
            } else if (obj instanceof String) {
                value = Double.parseDouble((String) obj);
            } else {
                continue; // 跳过无效数据
            }
            hourValues.computeIfAbsent(date, k -> new ArrayList<>()).add(value);

        }
       // 每天的数据求平均值
        Map<LocalDate, Double> hourAvgMap = new HashMap<>();//用来存放转换完平均数后的数据
        List<FamilyWeekVo> result=new ArrayList<>();//用来存放最后的封装结果
        for (Map.Entry<LocalDate, List<Double>> entry: hourValues.entrySet()) {
            LocalDate date = entry.getKey();
            List<Double> values = entry.getValue();
            //求每个时间点的平均数
            double avg = values.stream().mapToDouble(Double::doubleValue).average().orElse(0.0);
            hourAvgMap.put(date, avg);
            // 返回格式化后的日期（如 07.04）和平均值
            String formattedDate = String.format("%02d.%02d", date.getMonthValue(), date.getDayOfMonth());
//            Double avgValue = hourAvgMap.getOrDefault(date, 0);//没有值的话就设置成默认
            long longAvg = Math.round(avg); // 四舍五入转为 long
            FamilyWeekVo vio = FamilyWeekVo.builder()
                    .dataValue(longAvg)
                    .dateTime(formattedDate)
                    .build();
            result.add(vio);
        }
        return result;
    }
}
